<?php
namespace app\index\controller;
use app\common\lib\ChatGpt;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response;
class Key
{
    public function index()
    {
        $data=Request::param();
        return View::fetch();
    }
    public function show()
    {
        $data=Request::param();
        if($data){
            $data=Request::param();
            $data['key']=trim($data['key']);
            $data['msg']=trim($data['msg']);
            if(!$data['key']){
                $this->error("缺少key");
            }
            if(!$data['msg']){
                $this->error("缺少msg");
            }
            $client = new Client([
                'base_uri' => "https://ai.ruancc.com/v1/chat/completions",
                'timeout' => 200,
                'verify' => false,
            ]);
            $response = $client->post('', [
                'headers' => [
                    'Authorization' => "Bearer ".$data['key'],
                    'Content-Type' => 'application/json',
                ],
                'json' => [
                    'model' => 'gpt-4',
                    'messages' => [
                        [
                            "role" => "user",
                            "content" => $data['msg']
                        ],
                    ],
                ]
            ]);
            $data = json_decode($response->getBody(), true);
            $txt = $data['choices'][0]['message']['content'];
            dump($txt);
            $result=[];
            $result['prompt_token']=$data['usage']['prompt_tokens'];
            $result['prompt_price']=$result['prompt_token']*(0.0015*8/1000);
            $result['completion_token']=$data['usage']['completion_tokens'];
            $result['completion_price']=$result['completion_token']*(0.0020*8/1000);
            $result['all_token']=$result['prompt_token']+$result['completion_token'];
            $result['all_price']=$result['prompt_price']+$result['completion_price'];
            View::assign($result);
        }
        return View::fetch();
    }


}